#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "parse.h"

void parse_cmd(char *line, struct cmd *cmd)
{
	//printf("%s\n",line);
	char *temp = malloc(sizeof(line));
	strcpy(temp,line);
	
	int argc = 0;
	
	char *word = strtok(temp," ");
	while(word != NULL) {
		char *str = malloc(sizeof(word));
		strcpy(str,word);

		//printf("%s\n",word);
		if(str[0] == '>') {
			//printf("0\n");
			cmd->output = (char *)malloc(sizeof(str));
			strcpy(cmd->output,str);
			word = strtok(NULL," ");
			//if(word == NULL) printf("0\n");
			continue;
		}
		else if(str[0] == '<') {
			cmd->input = (char *)malloc(sizeof(str));
			strcpy(cmd->input,str);
			word = strtok(NULL," ");
			continue;
		}
		
		//printf("%s\n",word);
		cmd->argv[argc] =(char *)malloc(sizeof(str));
		strcpy(cmd->argv[argc],str);
		argc += 1;
		word = strtok(NULL," ");
	}
	cmd->argv[argc] = NULL;
	cmd->argc = argc;
	/*
	printf("%d\n",cmd->argc);
	int i = 0;
	for(i = 0 ; i < cmd->argc;i++) 
		printf("%s\n",cmd->argv[i]);
	if(cmd->input != NULL) printf("input :%s\n",cmd->input);
	if(cmd->output != NULL) printf("output :%s\n",cmd->output);
	*/
}

void dump_cmd(struct cmd *cmd)
{

}

int parse_pipe_cmd(char *line, struct cmd *cmdv)
{
	int cmdc = 0;
	char *temp;
	char *part = strtok_r(line,"|",&temp);
	while(part != NULL) {
		char *word = malloc(sizeof(part));
		strcpy(word,part);
		parse_cmd(word,cmdv + cmdc);
		cmdc += 1;
		part = strtok_r(NULL,"|",&temp);
	}
	return cmdc;
}

void dump_pipe_cmd(int cmdc, struct cmd *cmdv)
{
    int i;

    printf("pipe cmd, cmdc = %d\n", cmdc);
    for (i = 0; i < cmdc; i++) {
        struct cmd *cmd = cmdv + i;
        dump_cmd(cmd);
    }
}
